<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="7">
          <!-- queryInfo.query搜索功能 -->
          <el-input
            v-model="queryInfo.query"
            clearable
            @clear="getUserList"
            placeholder="搜索用户"
          >
            <el-button
              slot="append"
              @click="getUserList"
              icon="el-icon-search"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>
      <!-- 用户列表区域 -->
      <el-table :data="userList" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <!-- {{ scope.row }} 得到当前行的数据-->
            <!-- 开关 -->
            <el-switch
              v-model="scope.row.mg_state"
              @change="userStateChange(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <!-- //修改按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              round
              size="mini"
              @click="showEditdialog(scope.row.id)"
            ></el-button>
            <!-- //删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              round
              size="mini"
              @click="removeUserByid(scope.row.id)"
            ></el-button>
            <el-tooltip
              class="item"
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <!-- 分配角色按钮 -->
              <el-button
                type="warning"
                icon="el-icon-setting"
                round
                size="mini"
                @click="setRole(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页功能 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 3, 5]"
        :page-size="100"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 添加用户信息对话框 -->
    <el-dialog
      title="提示"
      :visible.sync="addDialogVisible"
      @close="addDialogClosed"
      width="50%"
    >
      <el-form
        :model="addForm"
        :rules="addFormrules"
        ref="addFormRef"
        label-width="70px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="adduser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户信息 -->
    <el-dialog
      title="修改用户信息"
      :visible.sync="editdialogVisible"
      width="50%"
      @close="editDialogClose"
    >
      <!--表单区域  -->
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="addFormrules"
        label-width="70px"
      >
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色对话框 -->
    <el-dialog
      title="分配角色"
      :visible.sync="settingUserDialogVisible"
      width="50%"
      @close="setRoleDialogClosed"
    >
      <div>
        <p>当前用户:{{ userInfo.username }}</p>
        <p>当前用户:{{ userInfo.role_name }}</p>
        <!-- 获取角色列表渲染 -->
        <el-select v-model="selectRoledId" placeholder="请选择">
          <el-option
            v-for="item in rolesList"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="settingUserDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "user",
  data() {
    //验证邮箱规则
    var checkEmail = (rule, value, cb) => {
      //正则
      const regEmail = /^([a-zA-A0-9_-])+@([a-zA-A0-9_-])+(\.[a-zA-A0-9_-])+/;
      if (regEmail.test(value)) {
        return cb();
      }
      cb(new Error("请输入合法的邮箱"));
    };
    //验证手机号校验规则
    var checkTel = (rule, value, cb) => {
      const regTel =
        /^(0|86|17951)?(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;
      if (regTel.test(value)) {
        return cb();
      }
      cb(new Error("请输入合法的手机号"));
    };

    return {
      //请求请求用户列表数据参数
      queryInfo: {
        //查询参数
        query: "",
        // 当前页码
        pagenum: 1,
        // 每页显示条数
        pagesize: 2,
      },
      //保存用户列表信息
      userList: [],
      total: 0,
      // 控制添加用户对话框的显示和隐藏
      addDialogVisible: false,
      //添加用户表单数据
      addForm: {
        username: "",
        password: "",
        email: "",
        tel: "",
      },
      //验证邮箱校验规则

      //校验规则
      addFormrules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 15,
            message: "请输入6-15个字符之间的密码",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          //特殊验证规则
          { validator: checkEmail, trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入电话", trigger: "blur" },
          { validator: checkTel, trigger: "blur" },
        ],
      },
      //编辑用户信息对话框
      editdialogVisible: false,
      //获取编辑当前的用户信息
      editForm: {},
      //分配角色
      settingUserDialogVisible: false,
      //当前角色信息
      userInfo: {},
      //角色列表
      rolesList: [],
      //已选中的角色
      selectRoledId: "",
    };
  },
  //页面创建后获取用户信息
  created() {
    this.getUserList();
  },
  methods: {
    //请求用户列表数据
    async getUserList() {
      const { data: res } = await this.$http.get("users", {
        params: this.queryInfo,
      });
      if (res.meta.status !== 200)
        return this.$message.error("获取用户列表失败");
      this.userList = res.data.users;
      this.total = res.data.total;
      console.log(res);
    },
    //pagesize变化
    handleSizeChange(newsize) {
      //console.log("@", newsize);
      this.queryInfo.pagesize = newsize;
      //重新获取用户列表
      this.getUserList();
    },
    //页码值的变化
    handleCurrentChange(newsize) {
      // console.log("#", newsize);
      this.queryInfo.pagenum = newsize;
      //重新获取用户列表
      this.getUserList();
    },
    //监听用户状态的变化
    async userStateChange(userInfo) {
      //console.log(userInfo);
      const { data: res } = await this.$http.put(
        `users/${userInfo.id}/state/${userInfo.mg_state}`
      );
      if (res.meta.status !== 200) {
        userInfo.mg_state = !userInfo.mg_state;
        return this.$message.error("更新用户状态失败");
      }
      this.$message.success("更新用户状态成功");
    },
    //对话框关闭后清空内容
    addDialogClosed() {
      this.$refs.addFormRef.resetFields();
    },
    //添加新用户
    adduser() {
      this.$refs.addFormRef.validate(async (valid) => {
        console.log(valid);
        //校验表单信息
        if (!valid) return;
        //校验成功添加用户
        const { data: res } = await this.$http.post("users", this.addForm);

        if (res.meta.status !== 201) {
          return this.$message.error("添加用户失败");
        }
        this.$message.success("添加用户成功");
        //添加成功后隐藏对话框
        this.addDialogVisible = false;
        //重新获取用户列表
        this.getUserList();
      });
    },
    //编辑用户信息
    async showEditdialog(id) {
      console.log(id);
      //先获取当前用户id
      const { data: res } = await this.$http.get("users/" + id);
      if (res.meta.status !== 200) {
        return this.$message.error("获取失败");
      }
      this.$message.success("获取成功");
      this.editForm = res.data;
      this.editdialogVisible = true;
    },
    //关闭用户信息修改页面重置信息
    editDialogClose() {
      this.$refs.editFormRef.resetFields();
    },
    //提交修改表单信息验证并提交
    editUserInfo() {
      this.$refs.editFormRef.validate(async (valid) => {
        console.log(valid);
        if (!valid) return;
        //发起用户修改信息数据请求
        const { data: res } = await this.$http.put(
          "users/" + this.editForm.id,
          {
            email: this.editForm.email,
            mobile: this.editForm.mobile,
          }
        );

        if (res.meta.status !== 200) {
          return this.$message.error("更用户失败");
        }

        //关闭对话框
        this.editdialogVisible = false;
        //刷新数据列表
        this.getUserList;
        //提示成功
        this.$message.success("更新数据成功");
      });
    },
    //删除用户信息
    async removeUserByid(id) {
      //弹窗是否删除用户信息
      const conformResoult = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      //确认删除， 返回的字符串为confirm
      //如果没有确认删除， 返回cancel
      //console.log(conformResoult);
      if (conformResoult !== "confirm") {
        return this.$message.info("已取消删除");
      }
      console.log("确认删除");
      //删除用户
      const { data: res } = await this.$http.delete("users/" + id);
      if (res.meta.status !== 200) {
        return this.$message.err("删除失败");
      }
      this.$message.success("删除成功");
      //更新用户列表
      this.getUserList();
    },
    //分配用户角色
    async setRole(userInfo) {
      //保存当前角色信息
      this.userInfo = userInfo;
      //获取所有角色列表
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status !== 200) {
        return this.$message.err("请求角色列表失败");
      }
      this.rolesList = res.data;
      this.settingUserDialogVisible = true;
    },
    //点击确定后更改角色信息
    async saveRoleInfo() {
      if (!this.selectRoledId) {
        return this.$message.err("请选择角色");
      }
      //更改用户角色
      const { data: res } = await this.$http.put(
        `users/${this.userInfo.id}/role`,
        {
          rid: this.selectRoledId,
        }
      );
      if (res.meta.status !== 200) {
        return this.$message.err("分配角色信息失败");
      }

      this.$message.success("分配角色信息成功");
      this.getUserList();
      this.settingUserDialogVisible = false;
    },
    //关闭分配角色对话框监听信息
    setRoleDialogClosed() {
      this.selectRoledId = "";
      this.userInfo = {};
    },
  },
};
</script>

<style lang="less" scoped>
</style>